%%% File    : login.erl
%%% Author  :  <>
%%% Description : 
%%% Created : 27 Mar 2011 by  <>

-module(login).

-export([login/2]).

login(Sock, Bin = <<_type:8, Id:32, Pwd/binary>>) ->
    case find_db(3) of
	Pid when is_pid(Pid) ->
	    case catch gen_server:call(Pid, {login, Id, binary_to_list(Pwd)}) of
		{'EXIT', Pid} ->
		    login(Sock, Bin);
		{ok, List} ->
		    gen_tcp:send(Sock, response(0, "logining")),
		    send_list(Sock, List);
		{error, _Reason} ->
		    gen_tcp:send(Sock, response(0, "errpasswd")),
		    gen_tcp:close(Sock),
		    exit(normal)
            end;
	_ ->
	    gen_tcp:send(Sock, response(0, "login failed")),
	    gen_tcp:close(Sock)
    end.


response(Type, Msg) when is_list(Msg) ->	
    B = <<Type:8>>,
    L = binary_to_list(B),
    list_to_binary(L ++ Msg).

find_db(0) ->
    io:format("not find db groups~n", []),
    undefined;
find_db(Try) ->
    case pg2:get_members(db) of
	{error, _Reason} ->
	    sleep(500),
	    find_db(Try-1);
	[] ->
	    sleep(500),
	    find_db(Try-1);
	_List ->
	    pg2:get_closest_pid(db)
    end.

sleep(T) ->
    receive
    after T ->
	    ok
    end.


send_list(Sock, []) ->
    B = <<1:8>>,
    L = binary_to_list(B),
    gen_tcp:send(Sock, list_to_binary(L ++ "fin"));
send_list(Sock, [{Id, Name}|T]) ->
    B = <<1:8, Id:32>>,
    L = binary_to_list(B),
    gen_tcp:send(Sock, list_to_binary(L ++ Name)),
 
    send_list(Sock, T).
